/**
 * Created by rockyren on 15/1/1.
 */
var commonDirective = angular.module('commonDirective', ['commonServices']);

commonDirective.directive('productList', function(){
  return {
    restrict: 'EA',
    scope: {
      products: '='
    },
    templateUrl: 'ngApp/common/tpls/product-list.html'
  }
});


commonDirective.directive('orderList', function(){
  return {
    restrict: 'EA',
    scope: {
      orderListType: '@',
      statusType: '='
    },
    controller: function($scope, orderServices, siftServices, errorShowServices) {

      function loadOrder(){
        orderServices.get()
          .success(function(data){
            //$scope.allOrderList = data;
            $scope.orderList = siftServices.siftByOrderStatus($scope.statusType, data);

          })
          .error(function(data){
            console.log(data.error);
          })
      }
      loadOrder();



      $scope.delete = function(id){
        if(confirm('确定删除订单？') == true){
          orderServices.destroy(id)
            .success(function(data){
              if(data.status && data.status == 'failure') {
                errorShowServices.alertErrorMessage('删除订单失败', data.message);
              }else {
                alert('删除订单成功');
                loadOrder();
              }
            })
            .error(function(data){
              console.log(data.error);
            });
        }

      };
      $scope.changeStatus = function(id, status){
        orderServices.update(id, {
          status: status
        })
          .success(function(data){
            if(data.status && data.status == 'failure') {
              errorShowServices.alertErrorMessage('修改状态失败', data.message);
            }else {

              loadOrder();
              console.log('修改状态成功');
            }
          })
          .error(function(data){
            console.log(data.error);
          })

      };


      //当状态改变时改变orderList
      $scope.$watch('statusType', function(newVal, oldVal){
        if(newVal != oldVal){
          //$scope.orderList = siftServices.siftByOrderStatus($scope.statusType, $scope.allOrderList);
          loadOrder();
        }
      });


    },
    templateUrl: 'ngApp/common/tpls/order-list.html'
  }
});

commonDirective.directive('orderInfo', function(){
  return {
    restrict: 'EA',
    scope: {
    },

    controller: function($scope, $routeParams, orderServices){
      function loadSingleOrder() {
        orderServices.show($routeParams.orderId)
          .success(function(data){
            console.log(data);
            $scope.orderInfo = data;
          })
          .error(function(data){

          });
      }
      loadSingleOrder();
    },

    templateUrl: 'ngApp/common/tpls/order-info.html'
  }
});